import java.util.Arrays;

/**
 * 基数排序
 *
 * @Author: wanqian
 * @Date: 2021/2/3 10:08
 */
public class RadixSort {

    public static int[] arr = {4, 3, 65, 12, 1, 6, 46, 64};

    public static void main(String[] args) {
//        int[] arr = new int[1000000];
//        for (int i = 0; i < arr.length; i++) {
//            arr[i] = (int) (Math.random() * 1000);
//        }
        System.out.println(String.format("排序前： %s", Arrays.toString(arr)));
        long start = System.currentTimeMillis();
        radixSort(arr);
        long end = System.currentTimeMillis();
        long consume = (end - start);
        System.out.println("耗时" + consume + "毫秒");
        System.out.println(String.format("排序后： %s", Arrays.toString(arr)));
    }

    public static void radixSort(int[] arr) {
        int[][] buckets = new int[10][arr.length];
        int[] bucketEle = new int[10];

        int max = arr[0];
        for (int i : arr) {
            if (i > max) {
                max = i;
            }
        }

        int round = String.valueOf(max).length();
        for (int i = 0; i < round; i++) {
            for (int val : arr) {
                int num = (int) (val / Math.pow(10, i)) % 10;
                buckets[num][bucketEle[num]++] = val;
            }

            int index = 0;
            for (int j = 0; j < 10; j++) {
                if (bucketEle[j] > 0) {
                    for (int k = 0; k < bucketEle[j]; k++) {
                        arr[index++] = buckets[j][k];
                    }
                }
                bucketEle[j] = 0;
            }
        }
    }
}
